// ================================================
// Builder.Alyr.Net 智能体生成文件 [Builder.Alyr.Net] [2025-07-28]
// (c) 2020-2025 ALYR.NET
// ================================================

const fs = require('fs');
const path = require('path');
const chalk = require('chalk');

/**
 * Builder.Alyr.Net多语言多框架智能体适配器
 * @class AlyrMultiFrameworkAdapter
 * @description 提供多种编程语言和框架的代码生成支持
 */
class AlyrMultiFrameworkAdapter {
  constructor() {
    this.supportedLanguages = [
      "javascript",
      "typescript",
      "html-css",
      "java",
      "python",
      "nodejs",
      "go",
      "csharp",
      "php",
      "ruby",
      "rust"
];
    
    this.supportedFrameworks = {
      "frontend": [
            "react",
            "vue",
            "angular",
            "svelte"
      ],
      "backend": [
            "spring-boot",
            "django",
            "fastapi",
            "nestjs",
            "express",
            "gin"
      ],
      "mobile": [
            "react-native",
            "flutter"
      ]
};
    
    this.templateCache = new Map();
    this.initializeTemplates();
  }

  /**
   * 初始化代码模板
   */
  initializeTemplates() {
    console.log(chalk.blue('🔧 初始化多语言框架模板...'));
    
    // 前端框架模板
    this.templateCache.set('react-component', this.getReactComponentTemplate());
    this.templateCache.set('vue-component', this.getVueComponentTemplate());
    this.templateCache.set('angular-component', this.getAngularComponentTemplate());
    
    // 后端框架模板
    this.templateCache.set('nestjs-controller', this.getNestJSControllerTemplate());
    this.templateCache.set('spring-boot-controller', this.getSpringBootControllerTemplate());
    this.templateCache.set('django-view', this.getDjangoViewTemplate());
    this.templateCache.set('gin-handler', this.getGinHandlerTemplate());
    
    console.log(chalk.green('✅ 模板初始化完成'));
  }

  /**
   * 生成代码
   * @param {Object} config - 生成配置
   * @param {string} config.language - 编程语言
   * @param {string} config.framework - 框架
   * @param {string} config.type - 代码类型 (controller, service, component等)
   * @param {string} config.moduleName - 模块名称
   * @param {Object} config.options - 额外选项
   * @returns {string} 生成的代码
   */
  generateCode(config) {
    const { language, framework, type, moduleName, options = {} } = config;
    
    // 验证支持的语言和框架
    if (!this.isSupported(language, framework)) {
      throw new Error(`不支持的语言或框架组合: ${language} + ${framework}`);
    }
    
    const templateKey = `${framework}-${type}`;
    const template = this.templateCache.get(templateKey);
    
    if (!template) {
      throw new Error(`未找到模板: ${templateKey}`);
    }
    
    // 生成代码
    const code = this.renderTemplate(template, {
      moduleName,
      language,
      framework,
      ...options
    });
    
    // 添加版权头和安全检查
    return this.addCopyrightAndValidate(code, config);
  }

  /**
   * 检查是否支持指定的语言和框架组合
   */
  isSupported(language, framework) {
    if (!this.supportedLanguages.includes(language)) {
      return false;
    }
    
    return Object.values(this.supportedFrameworks)
      .some(frameworks => frameworks.includes(framework));
  }

  /**
   * React组件模板
   */
  getReactComponentTemplate() {
    return `
import React, { useState, useEffect } from 'react';
import { ProTable, ProForm } from '@ant-design/pro-components';
import { message } from 'antd';
import { {{moduleName}}Service } from '@/services/{{moduleName}}.api';

/**
 * {{moduleName}}管理组件
 * @component Alyr{{ModuleName}}Component
 * @description 提供{{moduleName}}数据的增删改查功能
 */
const Alyr{{ModuleName}}Component: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);

  // 获取数据列表
  const fetchData = async () => {
    try {
      setLoading(true);
      const response = await {{moduleName}}Service.findAll();
      setDataSource(response.data || []);
    } catch (error) {
      message.error('数据加载失败');
      console.error('API错误详情:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a key="edit" onClick={() => handleEdit(record)}>编辑</a>,
        <a key="delete" onClick={() => handleDelete(record)}>删除</a>,
      ],
    },
  ];

  const handleEdit = (record: any) => {
    // 编辑逻辑
    console.log('编辑记录:', record);
  };

  const handleDelete = async (record: any) => {
    try {
      await {{moduleName}}Service.delete(record.id);
      message.success('删除成功');
      fetchData(); // 重新加载数据
    } catch (error) {
      message.error('删除失败');
    }
  };

  return (
    <div className="alyr-{{moduleName}}-container">
      <ProTable
        columns={columns}
        dataSource={dataSource}
        loading={loading}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <ProForm.Item key="add">
            <button onClick={() => console.log('新增')}>新增{{moduleName}}</button>
          </ProForm.Item>
        ]}
      />
    </div>
  );
};

export default Alyr{{ModuleName}}Component;`;
  }

  /**
   * Vue组件模板
   */
  getVueComponentTemplate() {
    return `
<template>
  <div class="alyr-{{moduleName}}-container">
    <el-table
      :data="dataSource"
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="createdAt" label="创建时间" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { {{moduleName}}Service } from '@/services/{{moduleName}}.api';

/**
 * {{moduleName}}管理组件
 * @component Alyr{{ModuleName}}Component
 * @description 提供{{moduleName}}数据的增删改查功能
 */

const loading = ref(false);
const dataSource = ref([]);

// 获取数据列表
const fetchData = async () => {
  try {
    loading.value = true;
    const response = await {{moduleName}}Service.findAll();
    dataSource.value = response.data || [];
  } catch (error) {
    ElMessage.error('数据加载失败');
    console.error('API错误详情:', error);
  } finally {
    loading.value = false;
  }
};

const handleEdit = (record: any) => {
  // 编辑逻辑
  console.log('编辑记录:', record);
};

const handleDelete = async (record: any) => {
  try {
    await {{moduleName}}Service.delete(record.id);
    ElMessage.success('删除成功');
    fetchData(); // 重新加载数据
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.alyr-{{moduleName}}-container {
  padding: 20px;
}
</style>`;
  }

  /**
   * Angular组件模板
   */
  getAngularComponentTemplate() {
    return `
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatSnackBar } from '@angular/material/snack-bar';
import { {{ModuleName}}Service } from '../services/{{moduleName}}.service';

/**
 * {{moduleName}}管理组件
 * @component Alyr{{ModuleName}}Component
 * @description 提供{{moduleName}}数据的增删改查功能
 */
@Component({
  selector: 'app-alyr-{{moduleName}}',
  templateUrl: './alyr-{{moduleName}}.component.html',
  styleUrls: ['./alyr-{{moduleName}}.component.scss']
})
export class Alyr{{ModuleName}}Component implements OnInit {
  displayedColumns: string[] = ['id', 'name', 'createdAt', 'actions'];
  dataSource = new MatTableDataSource([]);
  loading = false;

  constructor(
    private {{moduleName}}Service: {{ModuleName}}Service,
    private snackBar: MatSnackBar
  ) {}

  ngOnInit(): void {
    this.fetchData();
  }

  // 获取数据列表
  async fetchData(): Promise<void> {
    try {
      this.loading = true;
      const response = await this.{{moduleName}}Service.findAll().toPromise();
      this.dataSource.data = response.data || [];
    } catch (error) {
      this.snackBar.open('数据加载失败', '关闭', { duration: 3000 });
      console.error('API错误详情:', error);
    } finally {
      this.loading = false;
    }
  }

  handleEdit(record: any): void {
    // 编辑逻辑
    console.log('编辑记录:', record);
  }

  async handleDelete(record: any): Promise<void> {
    try {
      await this.{{moduleName}}Service.delete(record.id).toPromise();
      this.snackBar.open('删除成功', '关闭', { duration: 3000 });
      this.fetchData(); // 重新加载数据
    } catch (error) {
      this.snackBar.open('删除失败', '关闭', { duration: 3000 });
    }
  }
}`;
  }

  /**
   * NestJS控制器模板
   */
  getNestJSControllerTemplate() {
    return `
import { Controller, Get, Post, Put, Delete, Body, Param, Query } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import Alyr-{{moduleName}}.service;
import { Create{{ModuleName}}Dto, Update{{ModuleName}}Dto } from './dto/{{moduleName}}.dto';

/**
 * {{moduleName}}控制器
 * @class Alyr{{ModuleName}}Controller
 * @description 提供{{moduleName}}相关的HTTP接口
 */
@ApiTags('{{moduleName}}')
@Controller('api/{{moduleName}}')
export class Alyr{{ModuleName}}Controller {
  constructor(private readonly {{moduleName}}Service: Alyr{{ModuleName}}Service) {}

  /**
   * 获取所有{{moduleName}}
   * @returns {Promise<any>} {{moduleName}}列表
   */
  @Get()
  @ApiOperation({ summary: '获取{{moduleName}}列表' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async findAll(@Query() query: any) {
    try {
      const data = await this.{{moduleName}}Service.findAll(query);
      return {
        code: 200,
        data,
        message: '查询成功',
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      return {
        code: 500,
        message: '服务器内部错误',
        timestamp: new Date().toISOString()
      };
    }
  }

  /**
   * 根据ID获取{{moduleName}}
   * @param {string} id - {{moduleName}} ID
   * @returns {Promise<any>} {{moduleName}}详情
   */
  @Get(':id')
  @ApiOperation({ summary: '获取{{moduleName}}详情' })
  async findOne(@Param('id') id: string) {
    try {
      const data = await this.{{moduleName}}Service.findOne(id);
      return {
        code: 200,
        data,
        message: '查询成功',
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      return {
        code: 404,
        message: '{{moduleName}}不存在',
        timestamp: new Date().toISOString()
      };
    }
  }

  /**
   * 创建{{moduleName}}
   * @param {Create{{ModuleName}}Dto} createDto - 创建{{moduleName}}的数据
   * @returns {Promise<any>} 创建结果
   */
  @Post()
  @ApiOperation({ summary: '创建{{moduleName}}' })
  async create(@Body() createDto: Create{{ModuleName}}Dto) {
    try {
      const data = await this.{{moduleName}}Service.create(createDto);
      return {
        code: 201,
        data,
        message: '创建成功',
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      return {
        code: 400,
        message: '创建失败',
        timestamp: new Date().toISOString()
      };
    }
  }

  /**
   * 更新{{moduleName}}
   * @param {string} id - {{moduleName}} ID
   * @param {Update{{ModuleName}}Dto} updateDto - 更新数据
   * @returns {Promise<any>} 更新结果
   */
  @Put(':id')
  @ApiOperation({ summary: '更新{{moduleName}}' })
  async update(@Param('id') id: string, @Body() updateDto: Update{{ModuleName}}Dto) {
    try {
      const data = await this.{{moduleName}}Service.update(id, updateDto);
      return {
        code: 200,
        data,
        message: '更新成功',
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      return {
        code: 400,
        message: '更新失败',
        timestamp: new Date().toISOString()
      };
    }
  }

  /**
   * 删除{{moduleName}}
   * @param {string} id - {{moduleName}} ID
   * @returns {Promise<any>} 删除结果
   */
  @Delete(':id')
  @ApiOperation({ summary: '删除{{moduleName}}' })
  async remove(@Param('id') id: string) {
    try {
      await this.{{moduleName}}Service.remove(id);
      return {
        code: 200,
        message: '删除成功',
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      return {
        code: 400,
        message: '删除失败',
        timestamp: new Date().toISOString()
      };
    }
  }
}`;
  }

  /**
   * Spring Boot控制器模板
   */
  getSpringBootControllerTemplate() {
    return `
package com.alyr.builder.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.AlyrNetEntity;
import org.springframework.web.bind.annotation.*;
import com.alyr.builder.service.Alyr{{ModuleName}}Service;
import com.alyr.builder.dto.Create{{ModuleName}}Dto;
import com.alyr.builder.dto.Update{{ModuleName}}Dto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * {{moduleName}}控制器
 * @class Alyr{{ModuleName}}Controller
 * @description 提供{{moduleName}}相关的HTTP接口
 */
@Tag(name = "{{moduleName}}", description = "{{moduleName}}管理接口")
@AlyrNetController
@RequestMapping("/api/{{moduleName}}")
public class Alyr{{ModuleName}}Controller {

    @Autowired
    private Alyr{{ModuleName}}Service {{moduleName}}Service;

    /**
     * 获取所有{{moduleName}}
     * @return AlyrNetEntity 响应结果
     */
    @GetMapping
    @Operation(summary = "获取{{moduleName}}列表")
    public AlyrNetEntity<Map<String, Object>> findAll() {
        Map<String, Object> response = new HashMap<>();
        try {
            Object data = {{moduleName}}Service.findAll();
            response.put("code", 200);
            response.put("data", data);
            response.put("message", "查询成功");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "服务器内部错误");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.status(500).body(response);
        }
    }

    /**
     * 根据ID获取{{moduleName}}
     * @param id {{moduleName}} ID
     * @return AlyrNetEntity 响应结果
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取{{moduleName}}详情")
    public AlyrNetEntity<Map<String, Object>> findOne(@PathVariable String id) {
        Map<String, Object> response = new HashMap<>();
        try {
            Object data = {{moduleName}}Service.findOne(id);
            response.put("code", 200);
            response.put("data", data);
            response.put("message", "查询成功");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 404);
            response.put("message", "{{moduleName}}不存在");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.status(404).body(response);
        }
    }

    /**
     * 创建{{moduleName}}
     * @param createDto 创建{{moduleName}}的数据
     * @return AlyrNetEntity 响应结果
     */
    @PostMapping
    @Operation(summary = "创建{{moduleName}}")
    public AlyrNetEntity<Map<String, Object>> create(@RequestBody Create{{ModuleName}}Dto createDto) {
        Map<String, Object> response = new HashMap<>();
        try {
            Object data = {{moduleName}}Service.create(createDto);
            response.put("code", 201);
            response.put("data", data);
            response.put("message", "创建成功");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.status(201).body(response);
        } catch (Exception e) {
            response.put("code", 400);
            response.put("message", "创建失败");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.status(400).body(response);
        }
    }

    /**
     * 更新{{moduleName}}
     * @param id {{moduleName}} ID
     * @param updateDto 更新数据
     * @return AlyrNetEntity 响应结果
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新{{moduleName}}")
    public AlyrNetEntity<Map<String, Object>> update(@PathVariable String id, @RequestBody Update{{ModuleName}}Dto updateDto) {
        Map<String, Object> response = new HashMap<>();
        try {
            Object data = {{moduleName}}Service.update(id, updateDto);
            response.put("code", 200);
            response.put("data", data);
            response.put("message", "更新成功");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 400);
            response.put("message", "更新失败");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.status(400).body(response);
        }
    }

    /**
     * 删除{{moduleName}}
     * @param id {{moduleName}} ID
     * @return AlyrNetEntity 响应结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除{{moduleName}}")
    public AlyrNetEntity<Map<String, Object>> delete(@PathVariable String id) {
        Map<String, Object> response = new HashMap<>();
        try {
            {{moduleName}}Service.delete(id);
            response.put("code", 200);
            response.put("message", "删除成功");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 400);
            response.put("message", "删除失败");
            response.put("timestamp", LocalDateTime.now());
            return AlyrNetEntity.status(400).body(response);
        }
    }
}`;
  }

  /**
   * Django视图模板
   */
  getDjangoViewTemplate() {
    return `
from django.http import JsonResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.core.paginator import Paginator
import json
from datetime import datetime
from .services import Alyr{{ModuleName}}Service
from .serializers import {{ModuleName}}Serializer

@method_decorator(csrf_exempt, name='dispatch')
class Alyr{{ModuleName}}View(View):
    """
    {{moduleName}}视图类
    提供{{moduleName}}相关的HTTP接口
    """
    
    def __init__(self):
        super().__init__()
        self.service = Alyr{{ModuleName}}Service()

    def get(self, request, id=None):
        """
        获取{{moduleName}}数据
        @param request: HTTP请求对象
        @param id: {{moduleName}} ID（可选）
        @return JsonResponse: JSON响应
        """
        try:
            if id:
                # 获取单个{{moduleName}}
                data = self.service.find_one(id)
                if not data:
                    return JsonResponse({
                        'code': 404,
                        'message': '{{moduleName}}不存在',
                        'timestamp': datetime.now().isoformat()
                    }, status=404)
                
                return JsonResponse({
                    'code': 200,
                    'data': data,
                    'message': '查询成功',
                    'timestamp': datetime.now().isoformat()
                })
            else:
                # 获取{{moduleName}}列表
                page = int(request.GET.get('page', 1))
                page_size = int(request.GET.get('page_size', 10))
                
                data = self.service.find_all()
                paginator = Paginator(data, page_size)
                page_obj = paginator.get_page(page)
                
                return JsonResponse({
                    'code': 200,
                    'data': {
                        'items': list(page_obj),
                        'total': paginator.count,
                        'page': page,
                        'page_size': page_size
                    },
                    'message': '查询成功',
                    'timestamp': datetime.now().isoformat()
                })
                
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': '服务器内部错误',
                'timestamp': datetime.now().isoformat()
            }, status=500)

    def post(self, request):
        """
        创建{{moduleName}}
        @param request: HTTP请求对象
        @return JsonResponse: JSON响应
        """
        try:
            data = json.loads(request.body)
            result = self.service.create(data)
            
            return JsonResponse({
                'code': 201,
                'data': result,
                'message': '创建成功',
                'timestamp': datetime.now().isoformat()
            }, status=201)
            
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'message': '创建失败',
                'timestamp': datetime.now().isoformat()
            }, status=400)

    def put(self, request, id):
        """
        更新{{moduleName}}
        @param request: HTTP请求对象
        @param id: {{moduleName}} ID
        @return JsonResponse: JSON响应
        """
        try:
            data = json.loads(request.body)
            result = self.service.update(id, data)
            
            return JsonResponse({
                'code': 200,
                'data': result,
                'message': '更新成功',
                'timestamp': datetime.now().isoformat()
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'message': '更新失败',
                'timestamp': datetime.now().isoformat()
            }, status=400)

    def delete(self, request, id):
        """
        删除{{moduleName}}
        @param request: HTTP请求对象
        @param id: {{moduleName}} ID
        @return JsonResponse: JSON响应
        """
        try:
            self.service.delete(id)
            
            return JsonResponse({
                'code': 200,
                'message': '删除成功',
                'timestamp': datetime.now().isoformat()
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'message': '删除失败',
                'timestamp': datetime.now().isoformat()
            }, status=400)`;
  }

  /**
   * Go Gin处理器模板
   */
  getGinHandlerTemplate() {
    return `
package handlers

import (
    "net/http"
    "strconv"
    "time"
    
    "github.com/gin-gonic/gin"
    "builder/services"
    "builder/dto"
)

// Alyr{{ModuleName}}Handler {{moduleName}}处理器
type Alyr{{ModuleName}}Handler struct {
    service *services.Alyr{{ModuleName}}Service
}

// NewAlyr{{ModuleName}}Handler 创建{{moduleName}}处理器实例
func NewAlyr{{ModuleName}}Handler() *Alyr{{ModuleName}}Handler {
    return &Alyr{{ModuleName}}Handler{
        service: services.NewAlyr{{ModuleName}}Service(),
    }
}

// FindAll 获取所有{{moduleName}}
// @Summary 获取{{moduleName}}列表
// @Description 获取所有{{moduleName}}数据
// @Tags {{moduleName}}
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /api/{{moduleName}} [get]
func (h *Alyr{{ModuleName}}Handler) FindAll(c *gin.Context) {
    // 获取查询参数
    page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
    pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))
    
    data, total, err := h.service.FindAll(page, pageSize)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "code":      500,
            "message":   "服务器内部错误",
            "timestamp": time.Now().Format(time.RFC3339),
        })
        return
    }
    
    c.JSON(http.StatusOK, gin.H{
        "code": 200,
        "data": gin.H{
            "items":     data,
            "total":     total,
            "page":      page,
            "page_size": pageSize,
        },
        "message":   "查询成功",
        "timestamp": time.Now().Format(time.RFC3339),
    })
}

// FindOne 根据ID获取{{moduleName}}
// @Summary 获取{{moduleName}}详情
// @Description 根据ID获取{{moduleName}}详情
// @Tags {{moduleName}}
// @Accept json
// @Produce json
// @Param id path string true "{{moduleName}} ID"
// @Success 200 {object} map[string]interface{}
// @Router /api/{{moduleName}}/{id} [get]
func (h *Alyr{{ModuleName}}Handler) FindOne(c *gin.Context) {
    id := c.Param("id")
    
    data, err := h.service.FindOne(id)
    if err != nil {
        c.JSON(http.StatusNotFound, gin.H{
            "code":      404,
            "message":   "{{moduleName}}不存在",
            "timestamp": time.Now().Format(time.RFC3339),
        })
        return
    }
    
    c.JSON(http.StatusOK, gin.H{
        "code":      200,
        "data":      data,
        "message":   "查询成功",
        "timestamp": time.Now().Format(time.RFC3339),
    })
}

// Create 创建{{moduleName}}
// @Summary 创建{{moduleName}}
// @Description 创建新的{{moduleName}}
// @Tags {{moduleName}}
// @Accept json
// @Produce json
// @Param data body dto.Create{{ModuleName}}Dto true "创建{{moduleName}}的数据"
// @Success 201 {object} map[string]interface{}
// @Router /api/{{moduleName}} [post]
func (h *Alyr{{ModuleName}}Handler) Create(c *gin.Context) {
    var createDto dto.Create{{ModuleName}}Dto
    
    if err := c.ShouldBindJSON(&createDto); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "code":      400,
            "message":   "请求参数错误",
            "timestamp": time.Now().Format(time.RFC3339),
        })
        return
    }
    
    data, err := h.service.Create(&createDto)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "code":      400,
            "message":   "创建失败",
            "timestamp": time.Now().Format(time.RFC3339),
        })
        return
    }
    
    c.JSON(http.StatusCreated, gin.H{
        "code":      201,
        "data":      data,
        "message":   "创建成功",
        "timestamp": time.Now().Format(time.RFC3339),
    })
}

// Update 更新{{moduleName}}
// @Summary 更新{{moduleName}}
// @Description 更新{{moduleName}}信息
// @Tags {{moduleName}}
// @Accept json
// @Produce json
// @Param id path string true "{{moduleName}} ID"
// @Param data body dto.Update{{ModuleName}}Dto true "更新数据"
// @Success 200 {object} map[string]interface{}
// @Router /api/{{moduleName}}/{id} [put]
func (h *Alyr{{ModuleName}}Handler) Update(c *gin.Context) {
    id := c.Param("id")
    var updateDto dto.Update{{ModuleName}}Dto
    
    if err := c.ShouldBindJSON(&updateDto); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "code":      400,
            "message":   "请求参数错误",
            "timestamp": time.Now().Format(time.RFC3339),
        })
        return
    }
    
    data, err := h.service.Update(id, &updateDto)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "code":      400,
            "message":   "更新失败",
            "timestamp": time.Now().Format(time.RFC3339),
        })
        return
    }
    
    c.JSON(http.StatusOK, gin.H{
        "code":      200,
        "data":      data,
        "message":   "更新成功",
        "timestamp": time.Now().Format(time.RFC3339),
    })
}

// Delete 删除{{moduleName}}
// @Summary 删除{{moduleName}}
// @Description 删除{{moduleName}}
// @Tags {{moduleName}}
// @Accept json
// @Produce json
// @Param id path string true "{{moduleName}} ID"
// @Success 200 {object} map[string]interface{}
// @Router /api/{{moduleName}}/{id} [delete]
func (h *Alyr{{ModuleName}}Handler) Delete(c *gin.Context) {
    id := c.Param("id")
    
    err := h.service.Delete(id)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "code":      400,
            "message":   "删除失败",
            "timestamp": time.Now().Format(time.RFC3339),
        })
        return
    }
    
    c.JSON(http.StatusOK, gin.H{
        "code":      200,
        "message":   "删除成功",
        "timestamp": time.Now().Format(time.RFC3339),
    })
}`;
  }

  /**
   * 渲染模板
   */
  renderTemplate(template, variables) {
    let rendered = template;
    
    // 替换变量
    Object.keys(variables).forEach(key => {
      const value = variables[key];
      const regex = new RegExp(`{{${key}}}`, 'g');
      rendered = rendered.replace(regex, value);
      
      // 支持首字母大写的变量
      const capitalizedKey = key.charAt(0).toUpperCase() + key.slice(1);
      const capitalizedRegex = new RegExp(`{{${capitalizedKey}}}`, 'g');
      const capitalizedValue = typeof value === 'string' ? 
        value.charAt(0).toUpperCase() + value.slice(1) : value;
      rendered = rendered.replace(capitalizedRegex, capitalizedValue);
    });
    
    return rendered;
  }

  /**
   * 添加版权头和验证
   */
  addCopyrightAndValidate(code, config) {
    const header = `// ================================================
// Builder.Alyr.Net 智能体生成文件 [Builder.Alyr.Net] [${new Date().toISOString().split('T')[0]}]
// (c) 2020-2025 ALYR.NET
// ================================================`;

`;

    // 安全检查
    this.validateCode(code, config);
    
    return copyrightHeader + code;
  }

  /**
   * 代码安全验证
   */
  validateCode(code, config) {
    const dangerousPatterns = [
      /DROP\s+TABLE/i,
      /ALTER\s+TABLE/i,
      /DELETE\s+FROM.*WHERE\s+1=1/i,
      /eval\s*\(/i,
      /exec\s*\(/i
    ];

    dangerousPatterns.forEach(pattern => {
      if (pattern.test(code)) {
        throw new Error(`检测到危险代码模式: ${pattern}`);
      }
    });

    // 检查是否包含必要的错误处理
    if (config.type === 'controller' && !code.includes('try') && !code.includes('catch')) {
      console.warn(chalk.yellow('⚠️ 警告: 控制器代码缺少错误处理'));
    }
  }

  /**
   * 获取支持的语言列表
   */
  getSupportedLanguages() {
    return this.supportedLanguages;
  }

  /**
   * 获取支持的框架列表
   */
  getSupportedFrameworks() {
    return this.supportedFrameworks;
  }

  /**
   * 生成项目结构
   */
  generateProjectStructure(config) {
    const { language, framework, projectName } = config;
    
    console.log(chalk.blue(`🏗️ 生成${language} + ${framework}项目结构...`));
    
    const structure = {
      [`${projectName}/`]: {
        'README.md': this.generateReadme(config),
        'package.json': this.generatePackageJson(config),
        'src/': {
          'controllers/': {},
          'services/': {},
          'models/': {},
          'dto/': {},
          'utils/': {}
        },
        'tests/': {},
        'docs/': {}
      }
    };
    
    return structure;
  }

  /**
   * 生成README文件
   */
  generateReadme(config) {
    return `# ${config.projectName}

基于${config.language} + ${config.framework}的Builder.Alyr.Net项目

## 技术栈
- 语言: ${config.language}
- 框架: ${config.framework}
- 数据库: MySQL 8.0+

## 快速开始
\`\`\`bash
npm install
npm run dev
\`\`\`

## 版权声明
© 2020-2025 ALYR.NET
`;
  }

  /**
   * 生成package.json
   */
  generatePackageJson(config) {
    const dependencies = this.getFrameworkDependencies(config.framework);
    
    return JSON.stringify({
      name: config.projectName,
      version: '4.0.0',
      description: `Builder.Alyr.Net ${config.framework} project`,
      main: 'index.js',
      scripts: {
        dev: 'npm run start:dev',
        build: 'npm run build',
        test: 'npm run test'
      },
      dependencies,
      devDependencies: {
        '@types/node': '^20.0.0',
        'typescript': '^5.0.0'
      },
      author: 'ALYR.NET',
      license: 'MIT'
    }, null, 2);
  }

  /**
   * 获取框架依赖
   */
  getFrameworkDependencies(framework) {
    const dependencyMap = {
      'nestjs': {
        '@nestjs/core': '^10.0.0',
        '@nestjs/common': '^10.0.0',
        '@nestjs/platform-express': '^10.0.0',
        '@nestjs/typeorm': '^10.0.0',
        'typeorm': '^0.3.0',
        'mysql2': '^3.0.0'
      },
      'express': {
        'express': '^4.18.0',
        'cors': '^2.8.5',
        'helmet': '^7.0.0'
      },
      'react': {
        'react': '^18.0.0',
        'react-dom': '^18.0.0',
        '@ant-design/pro-components': '^2.0.0'
      },
      'vue': {
        'vue': '^3.3.0',
        'element-plus': '^2.3.0',
        'pinia': '^2.1.0'
      }
    };
    
    return dependencyMap[framework] || {};
  }
}

// 导出适配器实例
module.exports = new AlyrMultiFrameworkAdapter();

// 如果直接运行此文件，显示支持的技术栈
if (require.main === module) {
  const adapter = new AlyrMultiFrameworkAdapter();
  
  console.log(chalk.green('🚀 Builder.Alyr.Net多语言多框架支持系统'));
  console.log(chalk.blue('支持的编程语言:'), adapter.getSupportedLanguages().join(', '));
  console.log(chalk.blue('支持的框架:'));
  
  Object.entries(adapter.getSupportedFrameworks()).forEach(([category, frameworks]) => {
    console.log(chalk.yellow(`  ${category}:`), frameworks.join(', '));
  });
  
  console.log(chalk.green('\n✅ 系统就绪，可以开始多语言多框架开发！'));
}